package com.imooc.socialecom.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imooc.socialecom.base.JsonReturnType;
import com.imooc.socialecom.pojo.Item;
import com.imooc.socialecom.service.ItemService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/es")
public class ESController {

    @Autowired
    private ItemService itemService;

    @RequestMapping(value = "/importItemData", method = {RequestMethod.GET})
    public JsonReturnType importItemData() throws IOException {
        int size = 20;
        int currentPage = 1;
        int totalCount = itemService.count();
        int totalPage = (int) Math.ceil((double) totalCount / size);

        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));


        for (currentPage = 1; currentPage < totalPage + 1; currentPage++) {
            Page<Item> page = new Page<>(currentPage, size);
            List<Item> itemList = itemService.page(page).getRecords();

            // 创建批量请求
            BulkRequest bulkRequest = new BulkRequest();
            itemList.forEach(item -> {
                Map<String, Object> map = new HashMap<>();
                map.put("name", item.getName());
                bulkRequest.add(new IndexRequest("item").id(item.getId().toString()).source(map));
            });

            client.bulk(bulkRequest, RequestOptions.DEFAULT);

        }
        return JsonReturnType.createType(null);
    }
}
